package site.nullable.recorder.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import kotlinx.coroutines.delay
import site.nullable.recorder.data.model.Recording
import site.nullable.recorder.service.AudioPlayerService
import site.nullable.recorder.ui.viewmodel.RecordingViewModel

@Composable
fun RecordingList(
    viewModel: RecordingViewModel,
    modifier: Modifier = Modifier
) {
    val recordings by viewModel.recordings.collectAsStateWithLifecycle(initialValue = emptyList())
    val latestRecording by viewModel.latestRecording.collectAsStateWithLifecycle()

    // 收集播放状态和当前播放路径
    val playbackState by viewModel.playbackState.collectAsStateWithLifecycle()
    val currentPlayingPath by viewModel.currentPlayingPathFlow.collectAsStateWithLifecycle()

    // 录音列表的状态
    // 创建 LazyListState 并记住它
    val lazyListState = rememberLazyListState()

    // 状态：用于跟踪要删除的录音（null 表示没有要删除的录音）
    var recordingToDelete by remember { mutableStateOf<Recording?>(null) }

    // 使用 derivedStateOf 来跟踪是否有新的录音
    val shouldScrollToTop by remember(latestRecording) {
        derivedStateOf {
            latestRecording != null && recordings.isNotEmpty()
        }
    }

    // 当有新的录音时，自动滚动到顶部
    LaunchedEffect(shouldScrollToTop) {
        if (shouldScrollToTop) {
            // 延迟一小段时间确保列表已经更新
            delay(100)
            lazyListState.scrollToItem(0)
        }
    }

    // 删除确认对话框
    if (recordingToDelete != null) {
        DeleteConfirmationDialog(
            recording = recordingToDelete!!,
            onConfirmDelete = {
                viewModel.deleteRecording(recordingToDelete!!)
                recordingToDelete = null
            },
            onDismiss = {
                recordingToDelete = null
            }
        )
    }

    if (recordings.isEmpty()) {
        Box(
            modifier = modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "暂无录音",
                style = MaterialTheme.typography.bodyLarge,
                color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f)
            )
        }
    } else {
        Column(modifier = modifier) {
            LazyColumn(
                state = lazyListState,
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(recordings, key = { it.id }) { recording ->
                    val isPlaying = currentPlayingPath == recording.filePath &&
                                   playbackState is AudioPlayerService.PlaybackState.Playing
                    val isPaused = currentPlayingPath == recording.filePath &&
                                  playbackState is AudioPlayerService.PlaybackState.Paused

                    RecordingItem(
                        recording = recording,
                        isLatest = recording.id == latestRecording?.id,
                        isPlaying = isPlaying,
                        isPaused = isPaused,
                        onPlayClick = { viewModel.playRecording(recording) },
                        onPauseClick = { viewModel.pausePlaying() },
                        onResumeClick = { viewModel.resumePlaying() },
                        onStopClick = { viewModel.stopPlaying() },
                        onDeleteClick = {
                            // 点击删除时，设置要删除的录音，触发显示确认对话框
                            recordingToDelete = recording
                        }
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DeleteConfirmationDialog(
    recording: Recording,
    onConfirmDelete: () -> Unit,
    onDismiss: () -> Unit
) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = {
            Text(
                text = "删除录音",
                style = MaterialTheme.typography.headlineSmall
            )
        },
        text = {
            Column {
                Text(
                    text = "确定要删除这个录音文件吗？",
                    style = MaterialTheme.typography.bodyMedium
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "文件名：${recording.displayName}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = "创建时间：${recording.formattedDate}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = "文件大小：${recording.formattedSize}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "此操作不可撤销。",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.error
                )
            }
        },
        confirmButton = {
            Button(
                onClick = onConfirmDelete,
                colors = androidx.compose.material3.ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.error
                )
            ) {
                Text("删除")
            }
        },
        dismissButton = {
            Button(
                onClick = onDismiss
            ) {
                Text("取消")
            }
        }
    )
}

@Composable
fun RecordingItem(
    recording: Recording,
    isLatest: Boolean,
    isPlaying: Boolean,
    isPaused: Boolean,
    onPlayClick: () -> Unit,
    onPauseClick: () -> Unit,
    onResumeClick: () -> Unit,
    onStopClick: () -> Unit,
    onDeleteClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
                .background(
                    if (isLatest) MaterialTheme.colorScheme.primary.copy(alpha = 0.1f)
                    else Color.Transparent
                )
                .padding(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 播放控制按钮
            IconButton(
                onClick = {
                    when {
                        isPlaying -> onPauseClick()
                        isPaused -> onResumeClick()
                        else -> onPlayClick()
                    }
                },
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primary)
            ) {
                when {
                    isPlaying -> {
                        Icon(
                            imageVector = Icons.Default.Pause,
                            contentDescription = "暂停",
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                    isPaused -> {
                        Icon(
                            imageVector = Icons.Default.PlayArrow,
                            contentDescription = "继续播放",
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                    else -> {
                        Icon(
                            imageVector = Icons.Default.PlayArrow,
                            contentDescription = "播放",
                            tint = MaterialTheme.colorScheme.onPrimary,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                }
            }

            Spacer(modifier = Modifier.width(16.dp))

            // 录音信息
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = recording.displayName,
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.onBackground
                )

                Spacer(modifier = Modifier.height(4.dp))

                Text(
                    text = "${recording.formattedDate} • ${recording.formattedDuration} • ${recording.formattedSize}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f)
                )

                // 显示播放状态
                if (isPlaying || isPaused) {
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = if (isPlaying) "正在播放" else "已暂停",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.primary,
                        fontSize = 12.sp
                    )
                }

                if (isLatest) {
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "最新录音",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.primary,
                        fontSize = 12.sp
                    )
                }
            }

            // 停止按钮（仅在播放或暂停时显示）
            if (isPlaying || isPaused) {
                IconButton(
                    onClick = onStopClick
                ) {
                    Icon(
                        imageVector = Icons.Default.Stop,
                        contentDescription = "停止",
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }

            // 删除按钮
            IconButton(
                onClick = onDeleteClick
            ) {
                Icon(
                    imageVector = Icons.Default.Delete,
                    contentDescription = "删除",
                    tint = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f)
                )
            }
        }
    }
}
